﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation;
using System.IO;
using System.Reflection;

namespace NetworkScanner
{
    class OUILookup
    {
        /// <summary>
        /// Cache de busquedas
        /// </summary>
        static Dictionary<string, string> LookupCache = new Dictionary<string, string>();

        /// <summary>
        /// Informacion de ensamblado para recuperar archivo 'oui.txt' incrustado
        /// </summary>
        static Assembly Ensamblado = Assembly.GetExecutingAssembly();

        /// <summary>
        /// Realiza la resolucion de nombre de Vendor desde una MAC dada.
        /// </summary>
        /// <param name="p">Direccion fisica (MAC)</param>
        /// <returns>Nombre de fabricante</returns>
        public static string MACtoVendorLookup(PhysicalAddress p)
        {
            string vendor = "";
            try
            {
                string OUIhex = p.ToString().Substring(0, 6);
                if (!LookupCache.TryGetValue(OUIhex, out vendor))
                {
                    try
                    {
                        Ensamblado = Assembly.GetExecutingAssembly();
                        StreamReader stream = new StreamReader(Ensamblado.GetManifestResourceStream("NetworkScanner.oui.txt"));
                        string line;
                        while ((line = stream.ReadLine()) != null)
                        {
                            if (line.Length > 2 &&
                                line[0] != '\t' &&
                                line[2] != '-' &&
                                line.Substring(0, 6).CompareTo(OUIhex) == 0)
                            {
                                vendor = line.Split(new char[] { '\t' }).Last();
                                LookupCache.Add(OUIhex, vendor);
                                break;
                            }
                        }
                    }
                    catch (Exception) { }
                }
                return vendor;
            }
            catch (Exception)
            {
                return vendor;
            }
        }

    }
}
